package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import cc.ufinity.networkdiagnose.app.AppLogs;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.SimpleFTP;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;

public class FtpTestProxyWidget extends GeneralTestWidget {

	private Activity ctx;
	private Handler handlerChild;
	private FtpTestManager ftm;
	private Button backBtn;
	private Task task;
	private FTPTask ftpTask;
	private Handler ftpTestHandler;
//	private String localFilePath = Environment.getExternalStorageDirectory()+ "/ftptest/";
	private String localFilePath = ""; 
    private String remotePathUp ;
    private String remotePathDown = "/ftp/";
	//private String fileName = "ftp_test.png";
    private String fileNameDown = "2M.rar";
	private String fileNameUp = "1.doc";
	private int taskSize;
	private boolean taskProcessing;
	private int currentTaskNum;
	private int testedTimes;
    private int testedTimesUp = 0;
    private int testedTimesDown = 0;
	public static int testFlag = 0;
    public static int taskFlag = 0;  
	// private static final int COUNT = 3;
	private static final String TAG = "ftpTest";
	private boolean logouting = false;
	private boolean isFirst = true;
	private boolean isUpTestOver = false;
	private int ftpUpSuccessCount = 0;
	private int ftpDownSuccessCount = 0;

    private SimpleFTP simpleFTP;
	private BaseAdapter adapter;
    private WlanManager wlanManager;
    private TelManager tm;
    private FTPConfig ftpCongig;
	
	public FtpTestProxyWidget(Activity context, Handler handler, BaseAdapter adapter) {
		super(context);
		this.ctx = context; 
		this.handlerChild = handler;
		this.adapter = adapter;
		GlobalApp.ftpTestProxyWidget = this;
		
		remotePathUp = "/ftptest/"+ getTelNumber()+"/";
		localFilePath =  ctx.getFilesDir().getParent()+ File.separator + "ftptest" + File.separator; 
		inflate(ctx, R.layout.ftp_test_proxy_widget, this);
		backBtn = (Button) this.findViewById(R.id.ftp_test_proxy_btnback);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backToTask(ctx);
			}
		});
		ftpTestHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.FTP_UPLOAD_DONE:
					if(ftm.getCurrentUpSpeed() > 0) {
						ftpUpSuccessCount ++;
					}
					updateUploadProgress();
					break;
				case MessageWhat.FTP_DOWNLOAD_DONE:
					if(ftm.getCurrentDwSpeed() > 0) {
						ftpDownSuccessCount ++;
					}
					updateDownloadProgress();
					break;
				case MessageWhat.DONE:
					dismissProgressDialog();
					updateTestResult();
					//mSendBroadcast(ctx);
					handlerSendToTarget(handlerChild, MessageWhat.HANDLER_FTP);
					break;
				case MessageWhat.FTP_CONNECT_TIMEOUT:
					dismissProgressDialog();
					taskProcessing = false;
					showMessage(ctx, "FTP连接超时");
					//mSendBroadcast(ctx);
					handlerSendToTarget(handlerChild, MessageWhat.HANDLER_FTP);
					GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试连接超时");
					break;
				case MessageWhat.FTP_LOGIN_FAILED:
					dismissProgressDialog();
					taskProcessing = false;
					showMessage(ctx, "FTP连接超时");
					handlerSendToTarget(handlerChild, MessageWhat.HANDLER_FTP);
					GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试连接超时");
					break;
				case MessageWhat.DO_NEXT_TEST:
					//doPingTest();
					break;
				case SimpleFTP.CONNECTSUCCEED:
                	System.out.println("--------simpleFTP连接成功");
                	/*if(msg.arg1 > 0) {
                        showProgressDialog(ctx, "正在进行FTP测试...", msg.arg1);
                	} else {
                		showMessage(ctx, "simpleFTP连接成功");
                	}*/
                	break;
                case SimpleFTP.UPLOAD:
                	updateUploadProgress();
                	break;
                case SimpleFTP.DOWNLOAD:
                	updateDownloadProgress();
                	break;
                case SimpleFTP.UPOVER:

                	break;
                case SimpleFTP.DOWNOVER:
					updateTestResult();
					handlerSendToTarget(handlerChild, MessageWhat.HANDLER_FTP);
                	break;
                case SimpleFTP.TIMEOUTUP:
                    //上传超时
                    dismissProgressDialog();
                	break;
                case SimpleFTP.TIMEOUTDOWN:
                	//下载超时
                    dismissProgressDialog();
                    updateTestResult();
                    handlerSendToTarget(handlerChild, MessageWhat.HANDLER_FTP);
                	break;
				}
			}
		};
		
		wlanManager = new WlanManager(ctx);
    	tm = new TelManager(ctx);
		statFtpTest();
	}

	 private String getTelNumber(){
	    	TelManager telManager = new TelManager(ctx);
	    	String phoneNumber = telManager.getPhoneNumber();
	    	if (phoneNumber == null || phoneNumber.equals("")) {
	    		phoneNumber = GlobalApp.ftp_GUID;
			}
	    	return phoneNumber;
	    }
	
	private void initTestData() {
		if(wlanManager.checkNetworkType() == 1) {
			fileNameUp = GlobalApp.fileNameWlanUp;
        	fileNameDown = GlobalApp.fileNameWlanDown;
        	simpleFTP.setFileSizeDown(GlobalApp.fileSizeWlanDown);
        } else {
        	if(tm.getNetworkType().equals(WlanManager.TD) || tm.getNetworkType().equals("HSUPA")) {
        		fileNameUp = GlobalApp.fileNameTDUp;
            	fileNameDown = GlobalApp.fileNameTDDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeTDDown);
        	} else {
        		fileNameUp = GlobalApp.fileNameGSMUp;
            	fileNameDown = GlobalApp.fileNameGSMDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeGSMDown);
        	}
        }
		//String path = "cc/ufinity/networkdiagnose/widget/ftp_test.png"; // 图片存放的路径
		String path = "cc/ufinity/networkdiagnose/widget/" + fileNameUp; // 图片存放的路径
		InputStream is = ctx.getClassLoader().getResourceAsStream(path); // 得到图片流
		// FileInputStream fis = new FileInputStream(is);
		try {
			File f = new File(localFilePath);
			if (!f.exists()) {
				f.mkdirs();
			}
			FileOutputStream os = new FileOutputStream(localFilePath + fileNameUp);
			byte[] buffer = new byte[512];
			int ch = -1;
			while ((ch = is.read(buffer)) != -1) {
				os.write(buffer, 0, ch);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void initTestData2() {
		if(wlanManager.checkNetworkType() == 1) {
        	fileNameDown = GlobalApp.fileNameWlanDown;
        	simpleFTP.setFileSizeDown(GlobalApp.fileSizeWlanDown);
        } else {
        	if(tm.getNetworkType().equals(WlanManager.TD) || tm.getNetworkType().equals("HSUPA") ) {
            	fileNameDown = GlobalApp.fileNameTDDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeTDDown);
        	} else {
            	fileNameDown = GlobalApp.fileNameGSMDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeGSMDown);
        	}
        }
	}

	private void updateUploadProgress() {
		//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_FTP_test = temp;
		}
	//----------------------------------------------------------
		testedTimes ++;
        testedTimesUp++;
		adapter.notifyDataSetChanged();
		this.setDialogProgress(testedTimes);
		DecimalFormat df = new DecimalFormat("#0.00");
        float uploadSpeed = (float) simpleFTP.getUpY()[testedTimesUp-1];
		StringBuffer sb = new StringBuffer();
		sb.append("第").append(testedTimesUp).append("次"+ftpCongig.address+"上传速度为：")
				.append(df.format(uploadSpeed * 8));
		sb.append("Kb/s");
		
		//----------------------------------------------------------
		
		GlobalApp.result_FTP_test.append("第").append(testedTimesUp).append("次："+ftpCongig.address+"\n上传速度为：")
				.append(df.format(uploadSpeed * 8)).append("Kb/s\n");
	
//----------------------------------------------------------
	}

	private void updateDownloadProgress() {
		//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_FTP_test = temp;
		}
	//----------------------------------------------------------
		testedTimes ++;
		testedTimesDown ++;
		this.setDialogProgress(testedTimes);
		adapter.notifyDataSetChanged();
		DecimalFormat df = new DecimalFormat("#0.000");
		float dwSpeed = (float) simpleFTP.getDwY()[testedTimesDown-1];
		StringBuffer sb = new StringBuffer();
		sb.append("第").append(testedTimesDown).append("次"+ftpCongig.address+"下载速度为：")
				.append(df.format(dwSpeed*8));
		sb.append("Kb/s");
		//----------------------------------------------------------
		
		GlobalApp.result_FTP_test.append("第").append(testedTimesDown).append("次："+ftpCongig.address+"\n下载速度为：")
				.append(df.format(dwSpeed*8)).append("Kb/s\n");

	//---------------------------------------------------------- 
	}

	private void updateTestResult() {   
		DecimalFormat df = new DecimalFormat("0.000");
		double totalUpSpeed = 0.0;
        double totalDwSpeed = 0.0;
//        int frequency = 10;
        for(int i=0; i<testedTimesUp; i++) {
        	totalUpSpeed += simpleFTP.getUpY()[i];
        }
        for(int i=0; i<testedTimesDown; i++) {
        	totalDwSpeed += simpleFTP.getDwY()[i];
        }
		/*float avgUpRate = (float) (totalUpSpeed / frequency);
		float avgDwRate = (float) (totalDwSpeed / frequency);*/
		double avgUpRate = testedTimesUp==0? 0:totalUpSpeed / testedTimesUp;
        double avgDwRate = testedTimesDown==0? 0:totalDwSpeed / testedTimesDown;
		
		task.ftpDownAvgSuccessRate = df.format(avgDwRate) +"";
		task.ftpDownCount = testedTimesDown + "";
		task.ftpDownSuccessCount = testedTimesDown +"";
		task.ftpUpCount = testedTimesUp + "";
		task.ftpUpSuccessCount = testedTimesUp +"";
		task.ftpUpAvgSuccessRate = df.format(avgUpRate) +"";
		
System.out.println("task.ftpDownCount => " + task.ftpDownCount);
System.out.println("task.ftpDownSuccessCount => " + task.ftpDownSuccessCount);
System.out.println("task.ftpDownAvgSuccessRate => " + task.ftpDownAvgSuccessRate);
System.out.println("task.ftpUpCount => " + task.ftpUpCount);
System.out.println("task.ftpUpSuccessCount => " + task.ftpUpSuccessCount);
System.out.println("task.ftpUpAvgSuccessRate => " + task.ftpUpAvgSuccessRate);
		
		ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		StringBuffer s = new StringBuffer();
		s.append("总次数:").append(testedTimesUp + testedTimesDown);
		s.append(" 平均上载速度：").append(df.format(avgUpRate *8 )).append(" Kb/s");
		s.append(" 平均下载速度：").append(df.format(avgDwRate *8 )).append(" Kb/s");
		//平均速度为0 时 写入日志信息
		if (avgDwRate == 0 || avgDwRate == 0) {
			AppLogs.logData += SimpleFTP.strLog;
			System.out.println(SimpleFTP.strLog);
		}
		//----------------------------------------------------------
		
		GlobalApp.result_FTP_test.append("\n总次数:").append(testedTimesUp + testedTimesDown)
				.append("\n平均上传速度：").append(df.format(avgUpRate*8)).append(" Kb/s")
				.append("\n平均下载速度：").append(df.format(avgDwRate*8)).append(" Kb/s");

	//----------------------------------------------------------
	}

	public void statFtpTest() {
		ftpCongig = this.getFTPConfig(ctx);
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
		final List<FTPTask> tasks = task.ftpTasks;
		taskSize = tasks.size();
		//this.showProgressDialog(ctx, "正在进行FTP测试...", task.testCount*taskSize*2);
		SimpleFTP.strLog = "ftp-----------------------";//ftp日志信息
		new Thread() {
			public void run() {
				if(ftpCongig==null || ftpCongig.userName==null) {
					DBManager db = new DBManager(ctx);
					FTPConfig ftp = db.getFtp2();
	    	        if(ftp!=null) {
	    	        	db.saveFtp(ftp);  
	    	        	ftpCongig = ftp;
	    	        } 
	    	        db.release();
				} 
				if(ftpCongig==null || ftpCongig.userName==null) {
				} else {
					System.out.println(ftpCongig.address+"===="+ftpCongig.port+"========="+ftpCongig.userName+ftpCongig.password);
					simpleFTP = new SimpleFTP(ftpCongig.address, ftpCongig.port, 
							ftpCongig.userName, ftpCongig.password, ftpTestHandler);
					initTestData();
					boolean tempStor = false;
    	        	try {
    	                Thread.sleep(500);
    	            } catch (InterruptedException e) {}
        	        try {  
        	        	simpleFTP.connect();
        	        	try {
        	                Thread.sleep(500);
        	            } catch (InterruptedException e) {}
        	            try {
        	            	tempStor = simpleFTP.stor(localFilePath + fileNameUp, remotePathUp);
        	            }catch (Exception e) {
        	            	System.out.println("========= 文件上传： " + e.getMessage());
        	            }
        	            isUpTestOver = true;
        	            try {
        	                Thread.sleep(500);
        	            } catch (InterruptedException e) {}
        	            if(SimpleFTP.testing) {
        	            	if(!tempStor){
        	            		double upX[] = simpleFTP.getUpX();
        	            		double upY[] = simpleFTP.getUpY();
        	            		int i = 1;
        	            		while(i < 3) {
        	            			simpleFTP = new SimpleFTP(ftpCongig.address, ftpCongig.port, 
            	            	 			ftpCongig.userName, ftpCongig.password, ftpTestHandler);
            	            	 	simpleFTP.upX = upX;
            	            	 	simpleFTP.upY = upY;
                	            	initTestData2();
                	            	try {
                	            		simpleFTP.connect();
                	            		break;
                	            	} catch(IOException e) {
                	            		i++;
                	            	}
        	            		}
        	            	} 
        	            	try {
        	            		simpleFTP.get(localFilePath + fileNameDown, remotePathDown, fileNameDown);
        	            	} catch(IOException e) {
        	            		Message msg = ftpTestHandler.obtainMessage();
                	        	msg.what = SimpleFTP.DOWNOVER;
                	        	msg.sendToTarget();
        	            	}
        	            } else {
        	            	Message msg = ftpTestHandler.obtainMessage();
            	        	msg.what = SimpleFTP.TIMEOUTDOWN;
            	        	msg.sendToTarget();
        	            }
        	        } catch (IOException e) {
        	        	Message msg = ftpTestHandler.obtainMessage();
        	        	msg.what = MessageWhat.FTP_LOGIN_FAILED;
        	        	msg.sendToTarget();
        	            e.printStackTrace();
        	        } finally {
        	            try {
        	            	simpleFTP.disconnect();
        	            } catch (IOException e) {
        	                e.printStackTrace();
        	            }
        	        }
					/*if (ftm.login(ftp.address,ftp.port, ftp.userName, ftp.password)) {
						ftm.startFtpUpTest(task.testCount);
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							System.out.println("FTP测试线程等待出错：" + e.getMessage());
							Log.e(TAG, "FTP测试线程等待出错：", e);
						}
						ftm.startFtpDwTest(task.testCount);
					} else {
						ftm.sendMsg(MessageWhat.FTP_CONNECT_TIMEOUT);
					}*/
				}
			}
		}.start();
	}

	public int getTestedTimes() {
		return testedTimes;
	}

	public void setTestedTimes(int testedTimes) {
		this.testedTimes = testedTimes;
	}

	public int getTestCount() {
		if(isUpTestOver) {
			return testedTimesUp + 10;
		} else {
			return 20;
		}
		
	}
}
